$(function(){
	
	initPartnersReel();
	initPartnersHover();
	
	initFacebookAPI();
	
});

function initFacebookAPI() {
	(function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}
function fbShare() {
	var url = location.href;
	var win = window.open('https://www.facebook.com/sharer/sharer.php?u='+url, '_fb_share', 'width=400,height=300');
	win.focus();
}

function initPartnersReel() {
	$('#partners ul').wrap('<div class="screen" />');
	var screen = $('#partners .screen');
	var step = $("#partners li:first-child").outerWidth();
	var itemsVisible = $('#partners .screen').width() / step;
	var numItems = $("#partners li").length;
	var maxml = (numItems - itemsVisible) * step * -1;
	
	var ctrlPrev = $('<a href="javascript:void(0)" class="ctrl prev disabled">&laquo;</a>');
	screen.before(ctrlPrev);

	if(maxml==0) {
		ctrlPrev.css("visibility", "hidden");
		return;
	}
	
	var ctrlNext = $('<a href="javascript:void(0)" class="ctrl next">&raquo;</a>');
	screen.after(ctrlNext);
	
	var fadePrev = $('<div class="fade prev" />');
	screen.prepend(fadePrev);

	
	var fadeNext = $('<div class="fade next" />');
	screen.append(fadeNext);
	
	ctrlNext.click(function(){
		if($('#partners ul').attr('animating')) {
			return;
		}
		var ml = parseInt($("#partners ul").css("margin-left"));
		if(ml > maxml) {
			
			$('#partners .fade').show();
			$('#partners .ctrl').removeClass('disabled');
			if((ml-step) <= maxml) {
				$('#partners .fade.next').hide();
				$('#partners .ctrl.next').addClass('disabled');
			}
			
			$('#partners ul').attr("animating", 1).animate({
				marginLeft: ml - step
			}, {
				complete: function(){
					$(this).removeAttr("animating");
				}
			});
		}
	});
	ctrlPrev.click(function(){
		if($('#partners ul').attr('animating')) {
			return;
		}
		var itemsVisible = $('#partners .screen').width() / step;
		var ml = parseInt($("#partners ul").css("margin-left"));
		
		if(ml < 0) {
			
			$('#partners .fade').show();
			$('#partners .ctrl').removeClass('disabled');
			if((ml+step) >= 0) {
				$('#partners .fade.prev').hide();
				$('#partners .ctrl.prev').addClass('disabled');
			}
			
			$('#partners ul').attr("animating", 1).animate({
				marginLeft: ml + step
			}, {
				complete: function(){
					$(this).removeAttr("animating");
				}
			});
		}
	});
}

function initPartnersHover() {
	$("#partners img").mouseover(function(){
		$(this).attr("src", $(this).attr("src").replace(/\.(.*?)$/, ".hover.$1"));
	});
	
	$("#partners img").mouseout(function(){
		$(this).attr("src", $(this).attr("src").replace(/\.hover\.(.*?)$/, ".$1"));
	});
	
}